"use client"

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  IconActivity,
  IconMap,
  IconUsers,
  IconRefresh,
  IconDownload,
  IconPlay,
  IconPause
} from "@tabler/icons-react"

// 静态热力图数据（避免随机数）
const generateHeatmapData = () => {
  const data = []
  for (let x = 0; x < 20; x++) {
    for (let y = 0; y < 15; y++) {
      data.push({
        x,
        y,
        value: Math.sin(x / 20 * Math.PI) * Math.cos(y / 15 * Math.PI) * 50 + 50, // 固定模式
        intensity: 0.8 // 固定强度
      })
    }
  }
  return data
}

const HeatmapChart = () => {
  const data = generateHeatmapData()
  const maxValue = Math.max(...data.map(d => d.value))

  return (
    <div className="relative">
      <div className="grid grid-cols-20 gap-1 aspect-[4/3] bg-muted/10 p-4 rounded-lg">
        {data.map((point, index) => {
          const intensity = point.value / maxValue
          const color = intensity > 0.7 ? 'bg-error' :
            intensity > 0.4 ? 'bg-warning' : 'bg-primary'
          const opacity = intensity * 0.8 + 0.2

          return (
            <div
              key={index}
              className={`${color} rounded-sm transition-all hover:scale-110 cursor-pointer`}
              style={{ opacity }}
              title={`位置: (${point.x}, ${point.y}), 密度: ${point.value.toFixed(1)}`}
            />
          )
        })}
      </div>

      {/* 热力图图例 */}
      <div className="flex items-center justify-between mt-4">
        <div className="flex items-center space-x-4">
          <div className="flex items-center space-x-2">
            <div className="w-3 h-3 bg-primary rounded-sm opacity-60"></div>
            <span className="text-xs text-secondary">低密度</span>
          </div>
          <div className="flex items-center space-x-2">
            <div className="w-3 h-3 bg-warning rounded-sm opacity-80"></div>
            <span className="text-xs text-secondary">中密度</span>
          </div>
          <div className="flex items-center space-x-2">
            <div className="w-3 h-3 bg-error rounded-sm opacity-90"></div>
            <span className="text-xs text-secondary">高密度</span>
          </div>
        </div>
        <Badge variant="outline" className="text-xs">
          实时更新
        </Badge>
      </div>
    </div>
  )
}

const RealTimeChart = () => {
  const currentHour = new Date().getHours()
  // 使用固定的数据，避免随机数变化
  const data = Array.from({ length: 24 }, (_, i) => ({
    hour: i,
    value: Math.max(0, 50 + Math.sin(i / 24 * Math.PI * 2) * 30), // 移除 Math.random()
    isCurrent: i === currentHour
  }))

  const maxValue = Math.max(...data.map(d => d.value))

  return (
    <div className="relative">
      <div className="flex items-end justify-between h-48 gap-1">
        {data.map((item, index) => (
          <div key={index} className="flex-1 flex flex-col items-center">
            <div
              className={`w-full rounded-t ${item.isCurrent ? 'bg-primary' : 'bg-muted'
                } transition-all hover:bg-primary/80 cursor-pointer`}
              style={{ height: `${(item.value / maxValue) * 100}%` }}
              title={`${item.hour}:00 - 人流量: ${item.value.toFixed(0)}`}
            />
            <span className="text-xs text-secondary mt-1">
              {item.hour}
            </span>
          </div>
        ))}
      </div>

      <div className="flex items-center justify-between mt-4">
        <div className="text-sm text-secondary">
          24小时人流量分布
        </div>
        <div className="flex items-center space-x-2">
          <div className="w-3 h-3 bg-primary rounded"></div>
          <span className="text-xs text-secondary">当前时段</span>
        </div>
      </div>
    </div>
  )
}

const DeviceStatusChart = () => {
  const devices = [
    { name: 'MRI-01', status: 'running', utilization: 85 },
    { name: 'CT-02', status: 'running', utilization: 72 },
    { name: 'X-Ray-03', status: 'maintenance', utilization: 0 },
    { name: 'Echo-04', status: 'running', utilization: 91 },
    { name: 'MRI-05', status: 'idle', utilization: 15 },
    { name: 'CT-06', status: 'running', utilization: 68 }
  ]

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'running': return 'bg-success'
      case 'maintenance': return 'bg-warning'
      case 'idle': return 'bg-secondary'
      default: return 'bg-muted'
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'running': return '运行中'
      case 'maintenance': return '维护中'
      case 'idle': return '空闲'
      default: return '未知'
    }
  }

  return (
    <div className="space-y-3">
      {devices.map((device, index) => (
        <div key={index} className="flex items-center justify-between p-3 border rounded-lg hover:bg-muted/50 transition-colors">
          <div className="flex items-center space-x-3">
            <div className={`w-3 h-3 rounded-full ${getStatusColor(device.status)}`} />
            <div>
              <div className="font-medium">{device.name}</div>
              <div className="text-sm text-secondary">{getStatusText(device.status)}</div>
            </div>
          </div>

          <div className="flex items-center space-x-4">
            <div className="text-right">
              <div className="text-sm font-medium">{device.utilization}%</div>
              <div className="text-xs text-secondary">使用率</div>
            </div>

            <div className="w-24 h-2 bg-muted rounded-full overflow-hidden">
              <div
                className={`h-full ${getStatusColor(device.status)} transition-all`}
                style={{ width: `${device.utilization}%` }}
              />
            </div>
          </div>
        </div>
      ))}
    </div>
  )
}

export function MedicalCharts() {
  return (
    <div className="grid gap-6 md:grid-cols-2">
      {/* 热力图卡片 */}
      <Card className="md:col-span-2">
        <CardHeader className="flex flex-row items-center justify-between">
          <div>
            <CardTitle className="flex items-center gap-2">
              <IconMap className="w-5 h-5" />
              空间热力图
            </CardTitle>
            <CardDescription>
              实时显示医疗空间内的人员密度分布
            </CardDescription>
          </div>
          <div className="flex items-center space-x-2">
            <Button variant="outline" size="sm">
              <IconRefresh className="w-4 h-4 mr-2" />
              刷新
            </Button>
            <Button variant="outline" size="sm">
              <IconDownload className="w-4 h-4 mr-2" />
              导出
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <Tabs defaultValue="heatmap" className="w-full">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="heatmap">密度分布</TabsTrigger>
              <TabsTrigger value="trajectory">轨迹分析</TabsTrigger>
            </TabsList>
            <TabsContent value="heatmap" className="mt-4">
              <HeatmapChart />
            </TabsContent>
            <TabsContent value="trajectory" className="mt-4">
              <div className="text-center py-8 text-secondary">
                轨迹分析功能开发中...
              </div>
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>

      {/* 实时数据图表 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <IconUsers className="w-5 h-5" />
            人流量统计
          </CardTitle>
          <CardDescription>
            24小时实时人流量监控
          </CardDescription>
        </CardHeader>
        <CardContent>
          <RealTimeChart />
        </CardContent>
      </Card>

      {/* 设备状态监控 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <IconActivity className="w-5 h-5" />
            设备状态监控
          </CardTitle>
          <CardDescription>
            医疗设备实时状态与使用率
          </CardDescription>
        </CardHeader>
        <CardContent>
          <DeviceStatusChart />
        </CardContent>
      </Card>
    </div>
  )
} 